package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.BaseInfoBean;
import com.zlx.module_base.base_api.res_data.PurchaseVideoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.res_data.VideoBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 频道列表
 */
public class FrequencyAc extends BaseAc {

    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;

    private BaseInfoBean mBaseInfoBean;
    private String over;
    private int videoCount;
    private String title = "";
    private int page = 1;
    private String type = "1";
    private String state = "1";
    private String id = "";
    private List<VideoBean.InfoDTO.RecordsDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.ac_frequency_list;
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mAdapter.notifyItemChanged(msg.arg1);
                    break;
            }
        }
    };

    @Override
    public void initViews() {
        super.initViews();

        title = getIntent().getStringExtra("title");
        id = getIntent().getStringExtra("id");
        tv_title.setText(title);

        queryById();
        initRecyclerView();
        getVideoList();
        getBaseInfo();

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getVideoList();
                mAdapter.loadMoreComplete(false);
            }
        });
    }


    /**
     * 用户基本信息
     */
    private void getBaseInfo() {
        ApiUtil.getUserApi().getBaseInfo(SPUtil.getToken(this)).
                observe(this, new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<BaseInfoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseInfoBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (null != data.getData().getInfo()) {
                                            mBaseInfoBean = data.getData();
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();

                            }
                        }));
    }


    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this), (String) SPUtil.get(this, Constants.SP_ID, ""))
                .observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (null != data.getData().getInfo()) {
                                    if (data.getData().getInfo().size() > 0) {
                                        if (null != data.getData().getInfo().get(0).getResult()) {
                                            if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getVideoCount())) {
                                                videoCount = Integer.valueOf(data.getData().getInfo().get(0).getResult().getVideoCount());
                                                if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                    over = data.getData().getInfo().get(0).getResult().getMoney();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    private void initRecyclerView() {
        rv_data.setLayoutManager(new GridLayoutManager(this, 2));

        mAdapter = new CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO>(this, mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoBean.InfoDTO.RecordsDTO entity, int position) {

                GlideImgManager.glideLoader(FrequencyAc.this, entity.getCover(), holder.getView(R.id.iv_recommend), 1);

                GlideImgManager.glideLoader(FrequencyAc.this, entity.getAvatar(), holder.getView(R.id.iv_recommend_head), 0);

                holder.setText(R.id.tv_recommend_title, entity.getTitle());

                holder.setText(R.id.tv_recommend_nickname, entity.getNickname());

                holder.setText(R.id.tv_time, entity.getPeriod());

                if (entity.getIslike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_false);
                }

                if (entity.getIsVip().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.VISIBLE);
                } else {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.GONE);
                }
                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_authentication)).setVisibility(View.GONE);
                    }
                }
                holder.setText(R.id.tv_pageViews, entity.getPageViews());
                holder.setText(R.id.tv_fabulous, entity.getLikeCount());
                holder.setText(R.id.tv_comment_count, entity.getCommentCount());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_recommend;
            }
        };

        mAdapter.setLoadMore(true);

        rv_data.setAdapter(mAdapter);

        mAdapter.setOnLoadMoreListener(new CommonRecyclerViewAdapter.OnLoadMoreListener() {
            @Override
            public void onloadmore() {
                ++page;
                getVideoList();
            }
        });

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (mList.get(position).getIsMe().equals("1")) {
                    startActivity(new Intent(FrequencyAc.this, VideoDetailsAc.class)
                            .putExtra("id", mList.get(position).getId())
                            .putExtra("title", mList.get(position).getTitle()));
                } else {
                    if (mList.get(position).getIsPaid().equals("1")) {
                        //免费还有次数
                        if (videoCount > 0) {
                            dialogFreePlay(mList.get(position).getId()
                                    , mList.get(position).getTitle());
                        } else {
                            //没有免费次数
                            dialogMember();
                        }
                    } else {
                        //收费
                        if (mList.get(position).getIsFlag().equals("0")) {
                            //未购买 弹出购买窗口
                            dialogPay(
                                    mList.get(position).getId(),
                                    mList.get(position).getMoney());
                        } else {//已购买
                            startActivity(new Intent(FrequencyAc.this, VideoDetailsAc.class)
                                    .putExtra("id", mList.get(position).getId())
                                    .putExtra("title", mList.get(position).getTitle()));
                        }
                    }
                }
            }
        });
    }


    private void dialogMember() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_home_member, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        Button bt_member = view.findViewById(R.id.bt_member);

        bt_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(FrequencyAc.this, MemberAc.class)
                        .putExtra("data", mBaseInfoBean));
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);
        tv_over.setText("￥" + over);

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        purchaseVideo(id, money);
                        dialog.dismiss();
                    }
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 余额购买视频
     *
     * @param id
     * @param money
     */
    private void purchaseVideo(String id, String money) {
        dialogPass(id, money);
    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        PurchaseVideoBean purchaseVideoBean = new PurchaseVideoBean();
        purchaseVideoBean.setId(id);
        purchaseVideoBean.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(this);
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        purchaseVideoBean.setPayPassWord(passContent);

                        ApiUtil.getVideoApi().purchaseVideo(SPUtil.getToken(FrequencyAc.this),
                                purchaseVideoBean).observe(FrequencyAc.this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseBean> data) {
                                if (data.getData().getCode() == 0) {
                                    Toast.makeText(FrequencyAc.this, "购买成功", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    page = 1;
                                    getVideoList();
                                    queryById();
                                }
                            }
                        }));
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    private void getVideoList() {
        ApiUtil.getHomeApi().getVideoList(SPUtil.getToken(this),
                String.valueOf(page),
                type,
                state,
                id,
                "",
                "",
                "",
                "",
                "", "1"
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoBean> data) {
                sw_layout.setRefreshing(false);
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (null != data.getData().getInfo().get(0).getRecords()) {
                                        if (null != data.getData().getInfo().get(0).getRecords()) {
                                            List<VideoBean.InfoDTO.RecordsDTO> list = new ArrayList<>();
                                            for (int i = 0; i < data.getData().getInfo().get(0).getRecords().size(); i++) {
                                                if (data.getData().getInfo().get(0).getRecords().get(i).getCheckStatus().equals("1")) {
                                                    list.add(data.getData().getInfo().get(0).getRecords().get(i));
                                                }
                                            }
                                            if (page == 1) {
                                                mAdapter.refreshDatas(list, true);
                                            } else {
                                                mAdapter.refreshDatas(list, false);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
                mAdapter.notifyDataSetChanged();

                for (int i = 0; i < mList.size(); i++) {
                    final String video = mList.get(i).getVideo();
                    final int position = i;
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (!StringUt.isEmpty(video)) {
                                if (isValid(video) == true) {
                                    if (!StringUt.isEmpty(getPlayTime(video))) {
                                        String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(video)));
                                        mList.get(position).setPeriod(time);
                                        Message msg = new Message();
                                        msg.what = 1;
                                        msg.arg1 = position;
                                        handler.sendMessage(msg);
                                    }
                                }
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 弹出观看视频友情提示
     */
    private void dialogFreePlay(String id, String title) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_home_play, null);
        dialog.setContentView(view);

        RelativeLayout rl_close = view.findViewById(R.id.rl_close);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        RelativeLayout ll_dialog_play = view.findViewById(R.id.ll_dialog_play);

        ll_dialog_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(FrequencyAc.this, VideoDetailsAc.class)
                        .putExtra("id", id)
                        .putExtra("title", title));
                dialog.dismiss();
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    @OnClick(R.id.iv_back)
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }


    private String getPlayTime(String mUri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String duration = "";
        try {
            if (mUri != null) {
                HashMap headers = null;
                if (headers == null) {
                    headers = new HashMap();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }
            //注意地址 mUri= /storage/emulated/0/youshixiu/rectools/录屏专家190629113518.mp4    本地
            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return duration;
    }

    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }


    private boolean isValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }
        return false;
    }
}
